package com.opensource.svgaplayer.drawer;

import com.opensource.svgaplayer.IClickAreaListener;
import com.opensource.svgaplayer.SVGADynamicEntity;
import com.opensource.svgaplayer.SVGAVideoEntity;
import com.opensource.svgaplayer.entities.SVGAAudioEntity;
import com.opensource.svgaplayer.entities.SVGAPathEntity;
import com.opensource.svgaplayer.entities.SVGAVideoShapeEntity;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.components.StackLayout;
import ohos.agp.render.*;
import ohos.agp.utils.Color;
import ohos.agp.utils.Matrix;
import ohos.agp.utils.RectFloat;
import ohos.agp.utils.TextTool;
import ohos.media.audio.SoundPlayer;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.Size;
import ohos.utils.geo.Rect;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * ex.
 *
 * @author wl
 * @since 2021-06-28
 */
public class SVGACanvasDrawer extends SGVADrawer {
    private SVGADynamicEntity dynamicItem;
    private ShareValues sharedValues = new ShareValues();
    private HashMap<String, PixelMap> drawTextCache = new HashMap<>();
    private PathCache pathCache = new PathCache();
    private boolean[] beginIndexList = null;
    private boolean[] endIndexList = null;
    private SVGAVideoEntity videoItem;
    private int mCanvasWidth;
    private int mCanvasHeight;

    /**
     * SVGACanvasDrawer
     *
     * @param videoItem
     * @param dynamicItem
     */
    public SVGACanvasDrawer(SVGAVideoEntity videoItem, SVGADynamicEntity dynamicItem) {
        super(videoItem);
        this.videoItem = videoItem;
        this.dynamicItem = dynamicItem;
    }

    /**
     * drawFrame
     *
     * @param canvas     canvas
     * @param width      width
     * @param height     height
     * @param frameIndex frameIndex
     * @param scaleType  scaleType
     */
    @Override
    public void drawFrame(Canvas canvas, int width, int height, int frameIndex, Image.ScaleMode scaleType) {
        super.drawFrame(canvas, width, height, frameIndex, scaleType);
        mCanvasWidth = width;
        mCanvasHeight = height;
        playAudio(frameIndex);
        this.pathCache.onSizeChanged();
        List<SVGADrawerSprite> sprites = requestFrameSprites(frameIndex);
        if (sprites.size() <= 0) {
            return;
        }
        LinkedHashMap<String, SVGADrawerSprite> matteSprites = new LinkedHashMap<>();
        int saveID = -1;
        beginIndexList = null;
        endIndexList = null;
        boolean hasMatteLayer = false;
        String imageKey = sprites.get(0).getImageKey();
        if (imageKey != null) {
            if (imageKey.endsWith(".matte")) {
                hasMatteLayer = true;
            }
        }
        for (int i = 0; i < sprites.size(); i++) {
            int index = i;
            SVGADrawerSprite svgaDrawerSprite = sprites.get(i);
            String it = svgaDrawerSprite.getImageKey();
            if (it != null) {
                if (!hasMatteLayer) {
                    drawSprite(svgaDrawerSprite, canvas, width, height, frameIndex);
                    continue;
                }
                if (it.endsWith(".matte")) {
                    matteSprites.put(it, svgaDrawerSprite);
                    continue;
                }
            }
            if (isMatteBegin(index, sprites)) {
                RectFloat rectFloat = new RectFloat(0f, 0f, width, height);
                Paint paint = this.sharedValues.sharedPaint();
                paint.setAntiAlias(true);
                saveID = canvas.saveLayer(rectFloat, this.sharedValues.sharedPaint());
            }
            drawSprite(svgaDrawerSprite, canvas, width, height, frameIndex);
            if (isMatteEnd(index, sprites)) {
                SVGADrawerSprite sprite = matteSprites.get(svgaDrawerSprite.getMatteKey());
                if (sprite != null) {
                    drawSprite(sprite, this.sharedValues.shareMatteCanvas(width, height), width, height, frameIndex);
                    canvas.drawPixelMapHolder(new PixelMapHolder(this.sharedValues.sharedMatteBitmap()), 0f, 0f, this.sharedValues.shareMattePaint());
                    if (saveID != -1) {
                        canvas.restoreToCount(saveID);
                    } else {
                        canvas.restore();
                    }
                    continue;
                }
            }
        }
        releaseFrameSprites(sprites);
    }

    private boolean isMatteBegin(int spriteIndex, List<SVGADrawerSprite> sprites) {
        if (beginIndexList == null) {
            boolean[] boolArray = new boolean[sprites.size()];
            for (int i = 0; i < boolArray.length; i++) {
                boolArray[i] = false;
            }
            for (int i = 0; i < sprites.size(); i++) {
                int index = i;
                SVGADrawerSprite svgaDrawerSprite = sprites.get(i);
                if (svgaDrawerSprite.getImageKey() != null) {
                    if (svgaDrawerSprite.getImageKey().endsWith(".matte")) {
                        continue;
                    }
                }
                if (svgaDrawerSprite.getMatteKey() != null) {
                    String it = svgaDrawerSprite.getMatteKey();
                    if (it.length() > 0) {
                        SVGADrawerSprite lastSprite = sprites.get(index - 1);
                        if (lastSprite != null) {
                            if (lastSprite.getMatteKey() == null || lastSprite.getMatteKey().length() == 0) {
                                boolArray[index] = true;
                            } else {
                                if (!(lastSprite.getMatteKey().equals(svgaDrawerSprite.getMatteKey()))) {
                                    boolArray[index] = true;
                                }
                            }
                        }
                    }
                }
            }
            beginIndexList = boolArray;
        }
        return beginIndexList.length > spriteIndex ? beginIndexList[spriteIndex] : false;
    }

    private boolean isMatteEnd(int spriteIndex, List<SVGADrawerSprite> sprites) {
        if (endIndexList == null) {
            boolean[] boolArray = new boolean[sprites.size()];
            for (int i = 0; i < boolArray.length; i++) {
                boolArray[i] = false;
            }
            for (int i = 0; i < sprites.size(); i++) {
                int index = i;
                SVGADrawerSprite svgaDrawerSprite = sprites.get(i);
                if (svgaDrawerSprite.getImageKey() != null) {
                    if (svgaDrawerSprite.getImageKey().endsWith(".matte")) {
                        continue;
                    }
                }

                if (svgaDrawerSprite.getMatteKey() != null) {
                    String it = svgaDrawerSprite.getMatteKey();
                    if (it.length() > 0) {
                        if (index == sprites.size() - 1) {
                            boolArray[index] = true;
                        } else {
                            SVGADrawerSprite nextSprite = sprites.get(index + 1);
                            if (nextSprite != null) {
                                if (nextSprite.getMatteKey() == null || nextSprite.getMatteKey().length() == 0) {
                                    boolArray[index] = true;
                                } else {
                                    if (!(nextSprite.getMatteKey().equals(svgaDrawerSprite.getMatteKey()))) {
                                        boolArray[index] = true;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            endIndexList = boolArray;
        }
        return endIndexList.length > spriteIndex ? endIndexList[spriteIndex] : false;
    }

    private void playAudio(int frameIndex) {
        List<SVGAAudioEntity> audioList = videoItem.audioList;
        for (SVGAAudioEntity audio : audioList) {
            if (audio.getStartFrame() == frameIndex) {
                SoundPlayer soundPool = this.videoItem.soundPlayer;
                if (soundPool != null) {
                    Integer soundID = audio.getSoundID();
                    if (soundID != null) {
                        int playId = soundPool.play(soundID);
                        soundPool.setPlaySpeedRate(playId, 1f);
                        SoundPlayer.AudioVolumes audioVolumes = new SoundPlayer.AudioVolumes();
                        audioVolumes.setRearLeftVolume(1.0f);
                        audioVolumes.setRearRightVolume(1.0f);
                        soundPool.setVolume(soundID, audioVolumes);
                        soundPool.setLoop(playId, 1);
                        soundPool.setPriority(playId, 1);
                        audio.setPlayID(playId);
                    }
                }
            }
            if (audio.getEndFrame() <= frameIndex) {
                Integer playID = audio.getPlayID();
                if (playID != null) {
                    SoundPlayer soundPool = this.videoItem.soundPlayer;
                    if (soundPool != null) {
                        soundPool.deleteSound(audio.getSoundID());
                        soundPool.stop(playID);
                    }
                }
                audio.setPlayID(0);
            }
        }
    }

    static class ShareValues {
        private Paint sharedPaint = new Paint();
        private Path sharedPath = new Path();
        private Path sharedPath2 = new Path();
        private Matrix sharedMatrix = new Matrix();
        private Matrix sharedMatrix2 = new Matrix();
        private Paint shareMattePaint = new Paint();
        private PixelMap sharedMatteBitmap = null;

        Paint sharedPaint() {
            sharedPaint.reset();
            return sharedPaint;
        }

        Path sharedPath() {
            sharedPath.reset();
            return sharedPath;
        }

        Path sharedPath2() {
            sharedPath2.reset();
            return sharedPath2;
        }

        Matrix sharedMatrix() {
            sharedMatrix.reset();
            return sharedMatrix;
        }

        Matrix sharedMatrix2() {
            sharedMatrix2.reset();
            return sharedMatrix2;
        }

        Paint shareMattePaint() {
            shareMattePaint.setBlendMode(BlendMode.DST_IN);
            return shareMattePaint;
        }

        PixelMap sharedMatteBitmap() {
            return sharedMatteBitmap;
        }

        Canvas shareMatteCanvas(int width, int height) {
            PixelMap.InitializationOptions opts = new PixelMap.InitializationOptions();
            Size size = new Size(width, height);
            opts.size = size;
            opts.pixelFormat = PixelFormat.ARGB_8888;
            sharedMatteBitmap = PixelMap.create(opts);
            return new Canvas(new Texture(sharedMatteBitmap));
        }
    }

    class PathCache {
        private int canvasWidth = 0;
        private int canvasHeight = 0;
        private HashMap<SVGAVideoShapeEntity, Path> cache = new HashMap<>();

        void onSizeChanged() {
            if (this.canvasWidth != mCanvasWidth || this.canvasHeight != mCanvasHeight) {
                this.cache.clear();
            }
            this.canvasWidth = mCanvasWidth;
            this.canvasHeight = mCanvasHeight;
        }

        Path buildPath(SVGAVideoShapeEntity shape) {
            if (!this.cache.containsKey(shape)) {
                Path path = new Path();
                path.set(shape.getShapePath());
                this.cache.put(shape, path);
            }
            return this.cache.get(shape);
        }
    }

    private Matrix shareFrameMatrix(Matrix transform) {
        Matrix matrix = this.sharedValues.sharedMatrix();
        matrix.postScale(getScaleInfo().getScaleFx(), getScaleInfo().getScaleFy());
        matrix.postTranslate(getScaleInfo().getTranFx(), getScaleInfo().getTranFy());
        matrix.preConcat(transform);
        return matrix;
    }

    private void drawSprite(SVGADrawerSprite sprite, Canvas canvas, int width, int height, int frameIndex) {
        drawImage(sprite, canvas, width, height);
        drawShape(sprite, canvas);
        drawDynamic(sprite, canvas, frameIndex);
    }

    private void drawImage(SVGADrawerSprite sprite, Canvas canvas, int width, int height) {
        String imageKey = sprite.getImageKey();
        if (TextTool.isNullOrEmpty(imageKey)) {
            return;
        }


        Boolean isHidden = dynamicItem.getDynamicHidden().get(imageKey) == null ? false : dynamicItem.getDynamicHidden().get(imageKey);
        if (isHidden.booleanValue() == true) {
            return;
        }
        String bitmapKey = "";
        if (imageKey.endsWith(".matte")) {
            bitmapKey = imageKey.substring(0, imageKey.length() - 6);
        } else {
            bitmapKey = imageKey;
        }
        PixelMap drawingBitmap = dynamicItem.getDynamicImage().get(bitmapKey);
        if (drawingBitmap == null) {
            drawingBitmap = getVideoItem().imageMap.get(bitmapKey);
            if (drawingBitmap == null) {
                return;
            }
        }
        Matrix frameMatrix = shareFrameMatrix(sprite.getFrameEntity().getTransform());
        Paint paint = this.sharedValues.sharedPaint();
        paint.setAntiAlias(videoItem.isAntiAlias());
        paint.setFilterBitmap(videoItem.isAntiAlias());
        paint.setAlpha((float) (sprite.getFrameEntity().getAlpha()));
        if (sprite.getFrameEntity().getMaskPath() != null) {
            SVGAPathEntity maskPath = sprite.getFrameEntity().getMaskPath();
            if (maskPath == null) {
                return;
            }
            canvas.save();
            Path path = this.sharedValues.sharedPath();
            maskPath.buildPath(path);
            path.transform(frameMatrix);
            canvas.clipPath(path, Canvas.ClipOp.INTERSECT);
            frameMatrix.preScale((float) (sprite.getFrameEntity().getLayout().getWidth() / drawingBitmap.getImageInfo().size.width), (float) (sprite.getFrameEntity().getLayout().getHeight() / drawingBitmap.getImageInfo().size.height));
            if (!drawingBitmap.isReleased()) {
                canvas.setMatrix(frameMatrix);
                canvas.drawPixelMapHolder(new PixelMapHolder(drawingBitmap), 0, 0, paint);
                canvas.resetMatrix();
            }
            canvas.restore();
        } else {
            frameMatrix.preScale((float) (sprite.getFrameEntity().getLayout().getWidth() / drawingBitmap.getImageInfo().size.width), (float) (sprite.getFrameEntity().getLayout().getHeight() / drawingBitmap.getImageInfo().size.height));
            if (!drawingBitmap.isReleased()) {
                canvas.setMatrix(frameMatrix);
                canvas.drawPixelMapHolder(new PixelMapHolder(drawingBitmap), 0, 0, paint);
                canvas.resetMatrix();
            }
        }
        HashMap<String, IClickAreaListener> it = dynamicItem.getDynamicIClickArea();
        if (it != null) {
            IClickAreaListener listener = it.get(imageKey);
            if (listener != null) {
                float[] matrixArray = new float[]{0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f};

                frameMatrix.getElements(matrixArray);
                int x1 = new BigDecimal(drawingBitmap.getImageInfo().size.width).multiply(new BigDecimal(matrixArray[0]))
                        .add(new BigDecimal(matrixArray[2])).intValue();
                int y1 = new BigDecimal(drawingBitmap.getImageInfo().size.height).multiply(new BigDecimal(matrixArray[4]))
                        .add(new BigDecimal(matrixArray[5])).intValue();
                listener.onResponseArea(imageKey
                        , Float.valueOf(matrixArray[2]).intValue()
                        , Float.valueOf(matrixArray[5]).intValue()
                        , x1//Float.valueOf(drawingBitmap.getImageInfo().size.width * matrixArray[0] + matrixArray[2]).intValue()
                        , y1);//Float.valueOf(drawingBitmap.getImageInfo().size.height * matrixArray[4] + matrixArray[5]).intValue());
            }
        }
        drawTextOnBitmap(canvas, width, height, drawingBitmap, sprite, frameMatrix);
    }

    private void drawTextOnBitmap(Canvas canvas, int width, int height, PixelMap drawingBitmap, SVGADrawerSprite sprite, Matrix frameMatrix) {
        if (dynamicItem.isTextDirty()) {
            this.drawTextCache.clear();
            dynamicItem.setTextDirty(false);
        }

        String imageKey = sprite.getImageKey();
        if (imageKey == null) {
            return;
        }
        PixelMap textBitmap = null;
        String drawingText = dynamicItem.getDynamicText().get(imageKey);
        if (drawingText != null) {
            Paint drawingTextPaint = dynamicItem.getDynamicTextPaint().get(imageKey);
            if (drawingTextPaint != null) {
                PixelMap it = drawTextCache.get(imageKey);
                if (it == null) {
                    PixelMap.InitializationOptions options = new PixelMap.InitializationOptions();
                    Size size = new Size(drawingBitmap.getImageInfo().size.width, drawingBitmap.getImageInfo().size.height);
                    options.size = size;
                    options.pixelFormat = PixelFormat.ARGB_8888;
                    textBitmap = PixelMap.create(options);
                    Rect drawRect = new Rect(0, 0, drawingBitmap.getImageInfo().size.width, drawingBitmap.getImageInfo().size.height);
                    Canvas textCanvas = new Canvas(new Texture(textBitmap));
                    drawingTextPaint.setAntiAlias(true);
                    Paint.FontMetrics fontMetrics = drawingTextPaint.getFontMetrics();
                    double top = fontMetrics.top;
                    double bottom = fontMetrics.bottom;
                    float baseLineY =  (float)((double)drawRect.getCenterY() - top / 2.0F - bottom / 2.0F);
                    textCanvas.drawText(drawingTextPaint, drawingText, drawRect.getCenterX(), baseLineY);
                    drawTextCache.put(imageKey, textBitmap);
                } else {
                    textBitmap = it;
                }
            }
        }
        StackLayout boringLayout = dynamicItem.getDynamicBoringLayoutText().get(imageKey);
        if (boringLayout != null) {
            PixelMap it = drawTextCache.get(imageKey);
            if (it != null) {
                textBitmap = it;
            } else {
                PixelMap.InitializationOptions options = new PixelMap.InitializationOptions();
                Size size = new Size(drawingBitmap.getImageInfo().size.width, drawingBitmap.getImageInfo().size.height);
                options.size = size;
                options.pixelFormat = PixelFormat.ARGB_8888;
                textBitmap = PixelMap.create(options);
                PixelMap finalTextBitmap = textBitmap;
                boringLayout.addDrawTask(new Component.DrawTask() {
                    @Override
                    public void onDraw(Component component, Canvas canvas) {
                        canvas.setTexture(new Texture(finalTextBitmap));
                        canvas.translate(0f, (drawingBitmap.getImageInfo().size.width - boringLayout.getHeight()) / 2.0f);
                    }
                });
                boringLayout.invalidate();
                drawTextCache.put(imageKey, textBitmap);
            }
        }
        StackLayout staticLayout = dynamicItem.getDynamicStaticLayoutText().get(imageKey);
        if (staticLayout != null) {
            PixelMap it = drawTextCache.get(imageKey);
            if (it != null) {
                textBitmap = it;
            } else {
                PixelMap.InitializationOptions options = new PixelMap.InitializationOptions();
                Size size = new Size(drawingBitmap.getImageInfo().size.width, drawingBitmap.getImageInfo().size.height);
                options.size = size;
                options.pixelFormat = PixelFormat.ARGB_8888;
                textBitmap = PixelMap.create(options);
                PixelMap finalTextBitmap1 = textBitmap;
                staticLayout.addDrawTask(new Component.DrawTask() {
                    @Override
                    public void onDraw(Component component, Canvas canvas) {
                        canvas.setTexture(new Texture(finalTextBitmap1));
                        canvas.translate(0f, ((drawingBitmap.getImageInfo().size.width - staticLayout.getHeight()) / 2.0f));
                    }
                });
                staticLayout.invalidate();
                drawTextCache.put(imageKey, textBitmap);
            }
        }
        if (textBitmap != null) {
            Paint paint = this.sharedValues.sharedPaint();
            paint.setAntiAlias(videoItem.isAntiAlias());
            paint.setAlpha((float) sprite.getFrameEntity().getAlpha());
            if (sprite.getFrameEntity().getMaskPath() != null) {
                SVGAPathEntity maskPath = sprite.getFrameEntity().getMaskPath();
                if (maskPath == null) {
                    return;
                }
                canvas.save();
                canvas.setMatrix(frameMatrix);
                canvas.clipRect(0, 0, drawingBitmap.getImageInfo().size.width, drawingBitmap.getImageInfo().size.height);
                PixelMapShader bitmapShader = new PixelMapShader(new PixelMapHolder(textBitmap), Shader.TileMode.REPEAT_TILEMODE, Shader.TileMode.REPEAT_TILEMODE);
                paint.setShader(bitmapShader, Paint.ShaderType.PIXELMAP_SHADER);
                Path path = this.sharedValues.sharedPath();
                maskPath.buildPath(path);
                canvas.drawPath(path, paint);
                canvas.resetMatrix();
                canvas.restore();
            } else {
                paint.setFilterBitmap(videoItem.isAntiAlias());
                canvas.setMatrix(frameMatrix);
                canvas.drawPixelMapHolder(new PixelMapHolder(textBitmap), 0, 0, paint);
                canvas.resetMatrix();
            }
        }
    }

    private void drawShape(SVGADrawerSprite sprite, Canvas canvas) {
        Matrix frameMatrix = shareFrameMatrix(sprite.getFrameEntity().getTransform());
        List<SVGAVideoShapeEntity> shapes = sprite.getFrameEntity().getShapes();
        for (SVGAVideoShapeEntity shape : shapes) {
            shape.buildPath();
            Path it = shape.getShapePath();
            if (it != null) {
                Paint paint = this.sharedValues.sharedPaint();
                paint.setAntiAlias(videoItem.isAntiAlias());
                paint.setAlpha((float) sprite.getFrameEntity().getAlpha());
                Path path = this.sharedValues.sharedPath();
                path.reset();
                path.addPath(this.pathCache.buildPath(shape));
                Matrix shapeMatrix = this.sharedValues.sharedMatrix2();
                shapeMatrix.reset();
                Matrix transform = shape.getTransform();
                if (transform != null) {
                    shapeMatrix.postConcat(transform);
                }
                shapeMatrix.postConcat(frameMatrix);
                path.transform(shapeMatrix);
                if (shape.getStyles() != null) {
                    int fill = shape.getStyles().getFill();
                    paint.reset();
                    if (fill != 0x00000000) {
                        paint.setStyle(Paint.Style.FILL_STYLE);
                        paint.setColor(new Color(fill));
                        paint.setAlpha((float) sprite.getFrameEntity().getAlpha());
                        if (sprite.getFrameEntity().getMaskPath() != null) {
                            canvas.save();
                        }
                        SVGAPathEntity maskPath = sprite.getFrameEntity().getMaskPath();
                        if (maskPath != null) {
                            Path path2 = this.sharedValues.sharedPath2();
                            maskPath.buildPath(path2);
                            path2.transform(frameMatrix);
                            canvas.clipPath(path2, Canvas.ClipOp.INTERSECT);
                        }
                        canvas.drawPath(path, paint);
                        if (sprite.getFrameEntity().getMaskPath() != null) {
                            canvas.restore();
                        }
                    }
                }
                SVGAVideoShapeEntity.Styles styles = shape.getStyles();
                if (styles != null) {
                    float strokeWidth = styles.getStrokeWidth();
                    if (strokeWidth > 0) {
                        paint.setStyle(Paint.Style.STROKE_STYLE);
                        int stroke = styles.getStroke();
                        paint.setColor(new Color(stroke));
                        paint.setAlpha((float) sprite.getFrameEntity().getAlpha());
                        float scale = matrixScale(frameMatrix);
                        paint.setStrokeWidth(strokeWidth * scale);
                        String lineCap = styles.getLineCap();
                        if (!TextTool.isNullOrEmpty(lineCap)) {
                            switch (lineCap.toLowerCase()) {
                                case "butt":
                                    paint.setStrokeCap(Paint.StrokeCap.BUTT_CAP);
                                    break;
                                case "round":
                                    paint.setStrokeCap(Paint.StrokeCap.ROUND_CAP);
                                    break;
                                case "square":
                                    paint.setStrokeCap(Paint.StrokeCap.SQUARE_CAP);
                                    break;
                            }
                        }
                        String lineJoin = styles.getLineJoin();
                        if (!TextTool.isNullOrEmpty(lineJoin)) {
                            switch (lineJoin.toLowerCase()) {
                                case "miter":
                                    paint.setStrokeJoin(Paint.Join.MITER_JOIN);
                                    break;
                                case "round":
                                    paint.setStrokeJoin(Paint.Join.ROUND_JOIN);
                                    break;
                                case "bevel":
                                    paint.setStrokeJoin(Paint.Join.BEVEL_JOIN);
                                    break;
                            }
                        }
                        int miterLimit = styles.getMiterLimit();
                        paint.setStrokeMiter(miterLimit * scale);
                        float[] lineDash = styles.getLineDash();
                        if (lineDash != null) {
                            if (lineDash.length == 3 && (lineDash[0] > 0 || lineDash[1] > 0)) {
                                float[] temp = new float[2];
                                temp[0] = (lineDash[0] < 1.0f ? 1.0f : lineDash[0]) * scale;
                                temp[1] = (lineDash[1] < 0.1f ? 0.1f : lineDash[1]) * scale;
                                paint.setPathEffect(new PathEffect(temp, lineDash[2] * scale));
                            }
                        }
                        SVGAPathEntity maskPath = sprite.getFrameEntity().getMaskPath();
                        if (maskPath != null) {
                            canvas.save();
                            Path path2 = this.sharedValues.sharedPath2();
                            maskPath.buildPath(path2);
                            path2.transform(frameMatrix);
                            canvas.clipPath(path2, Canvas.ClipOp.INTERSECT);
                        }
                        canvas.drawPath(path, paint);
                        if (maskPath != null) {
                            canvas.restore();
                        }
                    }
                }
            }
        }
    }

    private float[] matrixScaleTempValues = new float[16];

    private float matrixScale(Matrix matrix) {
        matrix.getElements(matrixScaleTempValues);
        if (matrixScaleTempValues[0] == 0f) {
            return 0f;
        }
        if (matrixScaleTempValues[0] == 0f) {
            return 0f;
        }
        double A = matrixScaleTempValues[0];
        double B = matrixScaleTempValues[3];
        double C = matrixScaleTempValues[1];
        double D = matrixScaleTempValues[4];
        BigDecimal bigDecimal = new BigDecimal(A).multiply(new BigDecimal(D));
        BigDecimal bigDecimal1 = new BigDecimal(B).multiply(new BigDecimal(C));
        if (bigDecimal.compareTo(bigDecimal1)==0)return 0F;
//        if (A * D == B * C) return 0f;
        double scaleX = Math.sqrt(A * A + B * B);
        A /= scaleX;
        B /= scaleX;
        double skew = A * C + B * D;
        C -= A * skew;
        D -= B * skew;
        double scaleY = Math.sqrt(C * C + D * D);
        C /= scaleY;
        D /= scaleY;
        //  skew /= scaleY;
        if (A * D < B * C) {
            scaleX = -scaleX;
        }
        if (getScaleInfo().isRatioX()) {
            return Math.abs((float) scaleX);
        } else {
            return Math.abs((float) scaleY);
        }
    }

    private void drawDynamic(SVGADrawerSprite sprite, Canvas canvas, int frameIndex) {
        String imageKey = sprite.getImageKey();
        if (TextTool.isNullOrEmpty(imageKey)) {
            return;
        }
        SVGADynamicEntity.DynamicDrawLisenter lisenter = dynamicItem.getDynamicDrawer().get(imageKey);
        if (lisenter != null) {
            Matrix frameMatrix = shareFrameMatrix(sprite.getFrameEntity().getTransform());
            canvas.save();
            canvas.setMatrix(frameMatrix);
            lisenter.invoke(canvas, frameIndex);
            canvas.resetMatrix();
            canvas.restore();
        }
        SVGADynamicEntity.DynamicDrawSizeLisenter sizeLisenter = dynamicItem.getDynamicDrawerSized().get(imageKey);
        if (sizeLisenter != null) {
            Matrix frameMatrix = shareFrameMatrix(sprite.getFrameEntity().getTransform());
            canvas.save();
            canvas.setMatrix(frameMatrix);
            sizeLisenter.invoke(canvas, frameIndex, (int) (sprite.getFrameEntity().getLayout().getWidth()), (int) (sprite.getFrameEntity().getLayout().getHeight()));
            canvas.restore();
            canvas.resetMatrix();
        }
    }
}
